package zhengfuzhe.com.newupload1;

import android.app.ProgressDialog;

import android.content.Context;
import android.content.Intent;

import android.net.Uri;
import android.os.Bundle;

import android.util.Log;
import android.view.LayoutInflater;

import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;

import de.greenrobot.event.EventBus;
import zhengfuzhe.com.newupload1.base.BaseActivity;
import zhengfuzhe.com.newupload1.bean.LocalAppInfoBean;
import zhengfuzhe.com.newupload1.bean.NUDBean;
import zhengfuzhe.com.newupload1.bean.NetAppInfoBean;
import zhengfuzhe.com.newupload1.busMessager.MyInstalledMessage;
import zhengfuzhe.com.newupload1.download.DownloadInfo;
import zhengfuzhe.com.newupload1.download.DownloadManager;
import zhengfuzhe.com.newupload1.download.DownloadState;
import zhengfuzhe.com.newupload1.download.DownloadViewHolder;
import zhengfuzhe.com.newupload1.other.LocalAppManager;
import zhengfuzhe.com.newupload1.other.MatchAppUtil;

@ContentView(R.layout.activity_download)
public class DownloadActivity extends BaseActivity {

    @ViewInject(R.id.lv_download)
    private ListView downloadList;

    private DownloadManager downloadManager;
    private DownloadListAdapter downloadListAdapter;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        downloadManager = DownloadManager.getInstance();
        progressDialog = new ProgressDialog(DownloadActivity.this);
//        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setIcon(R.mipmap.ic_launcher);
        progressDialog.setMessage("Loading...");
        progressDialog.setCancelable(false);
        progressDialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                loadNetData();
            }
        }).start();
    }

    private void loadNetData() {

        RequestParams params = new RequestParams("http://webservice.conqueror.cn:8181/file/apkUpdate?perVersion=114&id=12345&imei=34555522");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("MyLog", "----onSuccess--------" + result);
                Gson gson = new Gson();
                NetAppInfoBean netAppInfoBean = gson.fromJson(result, NetAppInfoBean.class);
                ArrayList<NetAppInfoBean.ListBean> list = netAppInfoBean.list;
                ArrayList<LocalAppInfoBean> allApp = LocalAppManager.getInstance(DownloadActivity.this).getAllApp();
                ArrayList<NUDBean> needUpDateApp = MatchAppUtil.getInstance(DownloadActivity.this).getNeedUpDateApp(allApp, list);
                for (int i = 0; i < needUpDateApp.size(); i++) {
                    NUDBean nudBean = needUpDateApp.get(i);
                    PreferenceUtils.putString(getApplicationContext(), nudBean.packageName, nudBean.appName);
                    String fileSavePath = new File("/sdcard/NewDownload/" + nudBean.appName).getAbsolutePath();
                    PreferenceUtils.putString(getApplicationContext(), nudBean.appName, fileSavePath);
                    try {
                        DownloadManager.getInstance().startDownload(nudBean.url, nudBean.appName, "/sdcard/NewDownload/" + nudBean.appName, nudBean.packageName, true, false, null);
                        Log.e("MyLog", "-------------nudName------------------" + nudBean.appName);
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                }
                progressDialog.dismiss();
                if ((needUpDateApp.size() == 0)) {
                    Toast.makeText(DownloadActivity.this, "没有需要更新的数据", Toast.LENGTH_SHORT).show();
                }

                downloadListAdapter = new DownloadListAdapter();
                downloadList.setAdapter(downloadListAdapter);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.dismiss();
                Toast.makeText(DownloadActivity.this, "加载失败，请检查网络", Toast.LENGTH_SHORT).show();
                Log.e("MyLog", "----onError--------" + ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Log.e("MyLog", "----onCancelled--------" + cex);
            }

            @Override
            public void onFinished() {
                progressDialog.dismiss();
                Log.e("MyLog", "----onFinished--------");
            }
        });

    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        downloadManager.setIsFlag(false);
    }


    private class DownloadListAdapter extends BaseAdapter {

        private Context mContext;
        private final LayoutInflater mInflater;

        private DownloadListAdapter() {
            mContext = getBaseContext();
            mInflater = LayoutInflater.from(mContext);
        }

        @Override
        public int getCount() {
            if (downloadManager == null) return 0;
            return downloadManager.getDownloadListCount();
        }

        @Override
        public Object getItem(int i) {
            return downloadManager.getDownloadInfo(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            DownloadItemViewHolder holder = null;
            final DownloadInfo downloadInfo = downloadManager.getDownloadInfo(i);
            if (view == null) {
                view = mInflater.inflate(R.layout.download_item, null);
                holder = new DownloadItemViewHolder(view, downloadInfo);
                view.setTag(holder);
                holder.refresh();
            } else {
                holder = (DownloadItemViewHolder) view.getTag();
                holder.update(downloadInfo);
            }

            if (downloadInfo.getState().value() < DownloadState.FINISH.value()) {
                try {
                    downloadManager.startDownload(
                            downloadInfo.getUrl(),
                            downloadInfo.getLabel(),
                            downloadInfo.getFileSavePath(),
                            downloadInfo.getFileName(),
                            downloadInfo.isAutoResume(),
                            downloadInfo.isAutoRename(),
                            holder);
                } catch (DbException ex) {
                    Toast.makeText(x.app(), "添加下载失败", Toast.LENGTH_LONG).show();
                }
            }
            return view;
        }
    }

    public class DownloadItemViewHolder extends DownloadViewHolder {
        @ViewInject(R.id.download_label)
        TextView label;
        @ViewInject(R.id.download_state)
        TextView state;
        @ViewInject(R.id.download_size)
        TextView size;
        @ViewInject(R.id.download_pb)
        ProgressBar progressBar;
        @ViewInject(R.id.download_stop_btn)
        Button stopBtn;
        DecimalFormat df = new DecimalFormat("###.00");

        public DownloadItemViewHolder(View view, DownloadInfo downloadInfo) {
            super(view, downloadInfo);
            refresh();
        }

        @Event(R.id.download_stop_btn)
        private void toggleEvent(View view) {
            DownloadState state = downloadInfo.getState();
            switch (state) {
                case WATING:
                case STARTED:
                    downloadManager.stopDownload(downloadInfo);
                    break;
                case ERROR:
                case STOPED:
                    downloadManager.setIsFlag(true);
                    try {
                        downloadManager.startDownload(
                                downloadInfo.getUrl(),
                                downloadInfo.getLabel(),
                                downloadInfo.getFileSavePath(),
                                downloadInfo.getFileName(),
                                downloadInfo.isAutoResume(),
                                downloadInfo.isAutoRename(),
                                this);
                    } catch (DbException ex) {
                        Toast.makeText(x.app(), "添加下载失败", Toast.LENGTH_LONG).show();
                    }
                    break;
                case FINISH:

                    File install = new File(downloadInfo.getFileSavePath());
                    if (!install.exists()) {
                        downloadInfo.setState(DownloadState.ERROR);
                        downloadListAdapter.notifyDataSetChanged();
                        Toast.makeText(x.app(), "文件不存在，点击重新下载", Toast.LENGTH_LONG).show();
                        return;
                    }
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    intent.addCategory("android.intent.category.DEFAULT");
                    intent.setDataAndType(Uri.fromFile(new File(downloadInfo.getFileSavePath())),
                            "application/vnd.android.package-archive");
                    startActivity(intent);
                    break;
                default:
                    break;
            }
        }

        @Event(R.id.download_remove_btn)
        private void removeEvent(View view) {
            try {
                downloadManager.removeDownload(downloadInfo);
                downloadListAdapter.notifyDataSetChanged();
            } catch (DbException e) {
                Toast.makeText(x.app(), "移除任务失败", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void update(DownloadInfo downloadInfo) {
            super.update(downloadInfo);
            refresh();
        }

        @Override
        public void onWaiting() {
            refresh();
        }

        @Override
        public void onStarted() {
            refresh();
        }

        @Override
        public void onLoading(long total, long current) {

            double t = total / 1048576.0;
            double c = current / 1048576.0;
            size.setText(df.format(t) + "MB/" + df.format(c) + "MB");
            refresh();

        }

        @Override
        public void onSuccess(File result) {
            refresh();
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {

            refresh();
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {
            refresh();
        }

        public void refresh() {

            label.setText(downloadInfo.getLabel());
            state.setText(downloadInfo.getState().toString());
            progressBar.setProgress(downloadInfo.getProgress());

            stopBtn.setVisibility(View.VISIBLE);
            stopBtn.setText(x.app().getString(R.string.stop));
            DownloadState state = downloadInfo.getState();
            switch (state) {
                case WATING:
                case STARTED:
                    stopBtn.setText(x.app().getString(R.string.stop));
                    break;
                case ERROR:
                    stopBtn.setText(x.app().getString(R.string.reStart));
                    break;
                case STOPED:
                    stopBtn.setText(x.app().getString(R.string.start));
                    break;
                case FINISH:
                    stopBtn.setText("安装");
                    break;
                default:
                    stopBtn.setText(x.app().getString(R.string.start));
                    break;
            }
        }
    }


    public void onEventMainThread(MyInstalledMessage event) {
        Log.e("MyEventBus", "———MyEventBus能收到消息——111—");
//        if (event.getIsInstall() && (downloadManager.getDownloadListCount() == 0)) {
//            TextView textView = new TextView(DownloadActivity.this);
//            textView.setTextSize(30);
//            textView.setText("么有更多");
//        }
    }

    public void onEventAsync(MyInstalledMessage event) {
        String upDatedPackage = event.getUpDatedPackage();
        loadNetData();
        downloadManager.setIsFlag(false);
        Log.e("MyEventBus", "———MyEventBus能收到消息——222—" + upDatedPackage);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}